package UI;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import com.csvreader.CsvReader;

import Data.DbInterface;

/**
 * Main class and entry point of the application.
 */
public class Main
{
	/**
	 * Command-line argument: A path to a CSV file containing DB configuration parameters.
	 * The method loads the configuration, initialized the DB interface, and starts the game manager.
	 * 
	 * @param args Command line arguments
	 */
	public static void main(String[] args)
	{
		CsvReader reader = null;
		
		String serverAddr = null;
		String user = null;
		String password = null;
		
		try
		{
			if (args.length == 0)
				throw new IllegalArgumentException();
			
			reader = new CsvReader(args[0]);
			
			if (!reader.readHeaders() || !reader.readRecord())
				throw new IOException("Unable to read configuration header and record");
			
			serverAddr = reader.get("url");
			user = reader.get("user");
			password = reader.get("pass");
		}
		catch (FileNotFoundException e)
		{
			System.out.println("Invalid configuration file path\n" + e.getMessage());
			return;
		}
		catch (IOException e)
		{
			System.out.println("Invalid configuration content, should contain the fields: url, user, pass\n" + e.getMessage());
			return;
		}
		catch (IllegalArgumentException e)
		{
			System.out.println("Please provide a path to the configuration CSV file as the first argument");
			return;
		}
		finally
		{
			if (reader != null)
				reader.close();
		}
		
		if (!DbInterface.initialize(serverAddr, user, password))
		{
			Shell shell = SWTUtil.createSimpleShell();
			MessageBox mb = new MessageBox(shell);
			
			mb.setText("Error");
			mb.setMessage("Unable to initialize DB interface.");
			mb.open();
			
			shell.dispose();
			
			return;
		}
		
		GameManager manager = new GameManager();
		
		manager.start(false);
	}
}
